package com.dong.mjblog.util;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @Author:dxf
 * @Date:2020/12/6-12-06 21:44
 */
public class FileUtil {
    // 获取文件扩展名
    public static String getExtName(String fileName) {
        Pattern p2 = Pattern.compile("\\.([a-z0-9]+)$", Pattern.CASE_INSENSITIVE);
        Matcher m2 = p2.matcher(fileName);
        if (m2.find()) {
            return m2.group(1).toLowerCase();
        } else {
            return null;
        }
    }

    // 把字符串写入文件
    public static void writeFile(String fileName, String content) throws IOException {
        // 如果目标目录不存在，创建目录
        File txtfile = new File(fileName);
        String pfilePath = txtfile.getParent();
        File path = new File(pfilePath);

        String tmp = path.getParent();
        while (1 == 1) {
            File file = new File(tmp);
            if (!file.exists()) {
                tmp = file.getParent();
            } else {
                break;
            }
        }

        if (!path.exists()) {
            path.mkdirs();
        }

        while (1 == 1) {
            if (!tmp.equals(pfilePath)) {
                File file2 = new File(pfilePath);
                file2.setWritable(true, false);
                file2.setReadable(true, false);
                pfilePath = file2.getParent();
            } else {
                break;
            }
        }
        FileOutputStream out = new FileOutputStream(txtfile);
        out.write(content.getBytes());
        out.close();

    }

    // 获取文件内容
    public static String getTextContents(String fileName, String encode) throws IOException {
        if (encode == null)
            encode = "UTF-8";

        File f = new File(fileName);
        StringBuffer sb = new StringBuffer();
        InputStreamReader read = new InputStreamReader(new FileInputStream(f), encode);
        BufferedReader reader = new BufferedReader(read);
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }

        return sb.toString();
    }

    // 文件复制
    public static void copyFile(String srcPath, String destPath) throws IOException {
        File in = new File(srcPath);
        File out = new File(destPath);

        // 如果目标目录不存在，创建目录
        File path = new File(out.getParent());
        String tmp = path.getParent();
        while (1 == 1) {
            File file = new File(tmp);
            if (!file.exists()) {
                tmp = file.getParent();
            } else {
                break;
            }
        }

        if (!path.exists()) {
            path.mkdirs();
            // path.setWritable(true, false);
            // path.setReadable(true, false);
        }

        // 分配权限
        String pfilePath = out.getParent();
        while (1 == 1) {
            if (!tmp.equals(pfilePath)) {
                File file2 = new File(pfilePath);
                file2.setWritable(true, false);
                file2.setReadable(true, false);
                pfilePath = file2.getParent();
            } else {
                break;
            }
        }

        FileInputStream fis = new FileInputStream(in);
        FileOutputStream fos = new FileOutputStream(out);
        byte[] buf = new byte[1024];
        int i = 0;
        while ((i = fis.read(buf)) != -1) {
            fos.write(buf, 0, i);
        }
        fis.close();
        fos.close();
    }


    public static Map validateFile(MultipartFile file){
        Map result=new HashMap();

        result.put("result", 1);
        if(file==null){
            result.put("result", 0);
            result.put("msg", "参数有误");
        }
        String extName=FileUtil.getExtName(file.getOriginalFilename());
        String[] allowType={"xls","xlsx"};
        if(!Arrays.asList(allowType).contains(extName)){
            result.put("result", 0);
            result.put("msg", "文件类型不符合要求");

        }
        int sizeLimit=20;
        if(file.getSize()>sizeLimit*1024*1024){
            result.put("result", 0);
            result.put("msg", "文件太大，请选择"+sizeLimit+"MB以内的文件");
        }

        return result;
    }

    public static void deleteDir(String f) {
        File file = new File(f);
        FileUtil.deleteFile(file);
    }

    public static void deleteFile(File file) {
        if (file.exists()) {
            if (file.isFile()) {
                file.delete();
            } else if (file.isDirectory()) {
                File[] files = file.listFiles();
                for (int i = 0; i < files.length; i++) {
                    FileUtil.deleteFile(files[i]);
                }
                file.delete();
            }
        }
    }


    //删除指定目录下超过几天前的文件
    public static void deleteFile(String dir, double overDay) {
        File file = new File(dir);
        Date today = new Date();
        if (file.exists()) {
            if (file.isFile()) {
                long time = file.lastModified();
                Calendar cal=Calendar.getInstance();
                cal.setTimeInMillis(time);
                Date lastModified = cal.getTime();
                long days = getDistDates(today, lastModified);
                //
                if(days >= overDay){
                    file.delete();
                }
            } else if (file.isDirectory()) {
                File[] files = file.listFiles();
                for (int i = 0; i < files.length; i++) {
                    FileUtil.deleteFile(files[i].toString(),overDay);
                }
                //删除目录
                //file.delete();
            }
        }
    }


    //计算天数
    public static long getDistDates(Date startDate,Date endDate)
    {
        long totalDate = 0;
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(startDate);
        long timestart = calendar.getTimeInMillis();
        calendar.setTime(endDate);
        long timeend = calendar.getTimeInMillis();
        totalDate = Math.abs((timeend - timestart))/(1000*60*60*24);
        return totalDate;
    }




    /**
     * 把文件打成压缩包并保存在本地硬盘
     *
     * @param srcfiles
     * @param zipPath
     */
    public static void zipFiles(List srcfiles, String zipPath, HttpServletResponse response) {

        byte[] buf = new byte[4096];
        ZipOutputStream out = null;
        try {
            // 创建zip输出流
            out = new ZipOutputStream(new FileOutputStream(zipPath));

            // 循环将源文件列表添加到zip文件中
            for (int i = 0; i < srcfiles.size(); i++) {
                Map fileMap=(Map)srcfiles.get(i);
                File file = new File(fileMap.get("file")+"");
                FileInputStream in = new FileInputStream(file);
                String fileName = file.getName();
                String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
                String newfileName=fileMap.get("name")+"."+suffix;
                // 将文件名作为zip的Entry存入zip文件中
                out.putNextEntry(new ZipEntry(newfileName));
                int len;
                while ( (len = in.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }
                out.closeEntry();
                in.close();
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != out) {
                try {
                    //
                    out.close();
                    out = null;

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }


    //头部输出下载
    public static void downZipFiles(String zipName, String zipPath,HttpServletResponse response) {
        OutputStream out;
        try {
            out = response.getOutputStream();
            //头部输出下载
            response.setContentType("text/html; charset=UTF-8"); //设置编码字符
            response.setContentType("application/octet-stream"); //设置内容类型为下载类型
            response.setHeader("Content-disposition", "attachment;filename="+java.net.URLEncoder.encode(zipName,"UTF-8"));
            //将打包后的文件写到客户端，输出的方法同上，使用缓冲流输出
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(zipPath));
            byte[] buff = new byte[bis.available()];
            bis.read(buff);
            out.flush();//释放缓存
            out.write(buff);//输出数据文件

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }









}
